import Vue from 'vue'
import axios from 'axios'
import Qs from 'qs'
import {Notify} from "quasar";

const $axios = axios.create({
  baseURL: process.env.API,
  paramsSerializer(params) {
    return Qs.stringify(params, {indices: false})
  }
})

const token = localStorage.getItem('Authorization')
if (token) {
  $axios.defaults.headers.common.Authorization = token
}

// 添加响应拦截器
$axios.interceptors.response.use(function (response) {
  const data = response.data
  if (data) {
    if (data.error) {
      Notify.create({
        type: 'negative',
        message: data.error.error
      })
    } else if (data.message) {
      const cfg = {
        type: function (t) {
          switch (t) {
            case 'success':
              return 'positive'
            case 'warning':
              return 'warning'
            case 'error':
              return 'negative'
          }
        }(data.type),
        message: data.message.message
      }
      Notify.create(cfg)
      return data.message
    } else if (data.data) {
      return data.data
    }
  }
  return null;
}, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error);
});

Vue.prototype.$axios = $axios
